<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card区域 -->
    <el-card>
      <!-- 添加角色 -->
      <el-button type="primary" @click="addRolesdialogVisible=true">添加角色</el-button>
      <el-dialog
        title="添加角色"
        :visible.sync="addRolesdialogVisible"
        width="30%"
        @close="closeaddRolesDialog"
      >
        <el-form :model="rolesInfo" :rules="rolesInforules" ref="rolesInfoRef" label-width="100px">
          <el-form-item label="权限名称" prop="roleName">
            <el-input v-model="rolesInfo.roleName"></el-input>
          </el-form-item>
          <el-form-item label="权限描述" prop="roleDesc">
            <el-input type="textarea" v-model="rolesInfo.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRolesdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 角色列表区域 -->
      <el-table stripe border :data="rolosList" style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              type="flex"
              align="middle"
              v-for="(item1,i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom',i1===0?'bdtop':'']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="delectRoles(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  type="flex"
                  align="middle"
                  v-for="(item2,i2) in item1.children"
                  :key="item2.id"
                  :class="[,i2!==0?'bdtop':'']"
                >
                  <el-col :span="6">
                    <el-tag
                      closable
                      type="success"
                      @close="delectRoles(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="(item3) in item2.children"
                      :key="item3.id"
                      @close="delectRoles(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>{{scope.row}}</pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column width="300px" label="操作">
          <template slot-scope="cc">
            <el-button size="small " icon="el-icon-edit" type="primary">编辑</el-button>
            <el-button
              size="small "
              icon="el-icon-delete"
              type="danger"
              @click="delectRolesById(cc.row.id)"
            >删除</el-button>
            <el-button
              size="small "
              icon="el-icon-setting"
              type="warning"
              @click="openRolseRightDialog(cc.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="提示" :visible.sync="rolesdialogVisible" width="30%" @close="closerolesdialog">
      <p>{{currentClickname}}</p>
      <span>分配权限</span>
      <el-tree
        ref="setRolesRightRef"
        :data="rolesRightList"
        show-checkbox
        default-expand-all
        :default-checked-keys="checkList"
        node-key="id"
        :props="defaultProps"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="operateRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolosList: [],
      rolesdialogVisible: false,
      rolesRightList: [],
      defaultProps: {
        children: "children",
        label: "authName"
      },
      checkList: [],
      currentClickId: 0,
      currentClickname: "",
      addRolesdialogVisible: false,
      rolesInfo: {
        roleName: "",
        roleDesc: ""
      },
      rolesInforules: {
        roleName: [
          { required: true, message: "请输入权限名称", trigger: "blur" }
        ],
        roleDesc: [
          { required: true, message: "请输入权限描述", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 添加角色功能
    addRoles() {
      this.$refs.rolesInfoRef.validate(async config => {
        if (config) {
          const { data: res } = await this.$http.post(`roles`, this.rolesInfo);
          if (res.meta.status !== 201)
            return this.$message.error("创建角色失败");
          this.$message.success("创建角色成功");

          this.addRolesdialogVisible = false;
        }
      });
      this.getRolesList();
    },
    // 关闭添加角色页面
    closeaddRolesDialog() {
      this.$refs.rolesInfoRef.resetFields();
    },
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolosList = res.data;
    },
    // 删除角色
    delectRolesById(id) {
      this.$confirm("此操作将删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`);

          if (res.meta.status !== 200)
            return this.$message.error("删除角色失败");
          this.$message({
            type: "success",
            message: "删除角色成功!"
          });
          this.getRolesList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    delectRoles(roles, index) {
      this.$confirm("此操作将删除该项权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/` + roles.id + `/rights/` + index
          );
          if (res.meta.status !== 200)
            return this.$message.error("取消权限失败");
          roles.children = res.data;
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async operateRoles() {
      const keyArr = [
        ...this.$refs.setRolesRightRef.getCheckedKeys(),
        ...this.$refs.setRolesRightRef.getHalfCheckedKeys()
      ];
      const newArr = keyArr.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.currentClickId}/rights`,
        {
          rids: newArr
        }
      );
      if (res.meta.status !== 200)
        return this.$message.error("更新用户权限失败");
      this.$message.success("更新用户权限成功");
      this.getRolesList();
      this.rolesdialogVisible = false;
    },
    closerolesdialog() {
      this.checkList = [];
    },
    async openRolseRightDialog(userInfo) {
      this.rolesdialogVisible = true;

      this.currentClickId = userInfo.id;
      this.currentClickname = userInfo.roleName;
      this.getLeafKeys(userInfo, this.checkList);

      const { data: res } = await this.$http.get(`rights/tree`);
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败");
      this.rolesRightList = res.data;
    },
    // 遍历当前节点是否为三级节点
    getLeafKeys(node, arr) {
      if (!node.children) {
        arr.push(node.id);
      } else {
        node.children.forEach((item, i) => {
          if (!item.children) {
            arr.push(item.id);
          } else {
            this.getLeafKeys(item, arr);
          }
        });
      }
    }
  },
  created() {
    this.getRolesList();
  }
};
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eeeeee;
}
.bdbottom {
  border-bottom: 1px solid #eeeeee;
}
</style>